	/**
	 *      Simple.java
	 *      
	 *      Copyright 2008 
	 *      @author 	Thomas Wolfe <tomwolfe@gmail.com>
	 *      @version	0.2
	 *      
	 *      This program is free software; you can redistribute it and/or modify
	 *      it under the terms of the GNU General Public License as published by
	 *      the Free Software Foundation; either version 2 of the License, or
	 *      (at your option) any later version.
	 *      
	 *      This program is distributed in the hope that it will be useful,
	 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
	 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	 *      GNU General Public License for more details.
	 *      
	 *      You should have received a copy of the GNU General Public License
	 *      along with this program; if not, write to the Free Software
	 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
	 *      MA 02110-1301, USA.
	 */


package org.testing;

// Code as if whoever maintains your program is a violent psychopath who knows where you live.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.gnome.gdk.Event;
import org.gnome.glade.Glade;
import org.gnome.glade.XML;
import org.gnome.gtk.*;
import org.gnome.gtk.Button.CLICKED;
import org.gnome.gtk.ComboBox.CHANGED;
import org.gnome.gtk.Window.DELETE_EVENT;

public class Simple 
{
	int currentTeam, cardNumVal, numCards, numTeams;
	CardStorage cardStore,validCardStore;
	TeamStorage teamStore;
	Card currentCard,insCard;
	XML glade;
	Window window;
	// Current Card
	// buttons
	Button correct, incorrect, newGame;
	// labels
	Label mustSetOptionsNewGame,mainWord,label1,label2,label3,label4,
		label5,label6,cardNumReal,currentTeamNumReal,currCardRatingValue,
		scoreLabel;
	
	// Options
	// Buttons
	Button useDefaultOptions, clearOptions;
	// ComboBox
	ComboBox numTeamsBox,numCardsBox,numSecondsBox,maxDifficulty,
		selectTeamBox,minOverallRatingBox,difficultyBoxRating,
		overallBoxRating;
	
	// Add Card
	// Buttons
	Button addCard, clearAddCard;
	// Entry
	Entry mainEntry, entry1, entry2, entry3, entry4, entry5, entry6;
	// Label
	Label successfullAdd;
	// ComboBox
	ComboBox initialOverallRatingBox;
	
	// Read/write
	// Buttons
	Button saveButton,loadButton;
	
	/**
	 * Sole Constructor
	 */

	public Simple() throws FileNotFoundException
	{

		glade = Glade.parse("glade3.glade", "window1");
		
		window = (Window) glade.getWidget("window1");
		
		// Allows program to terminate on close
		window.connect(new DELETE_EVENT() {
            public boolean onDeleteEvent(Widget source, Event event) {
                Gtk.mainQuit();
                return false;
            }
        });
		cardStore=new CardStorage();
		validCardStore=new CardStorage();
		teamStore=new TeamStorage();

		
		// Add Card
		mainEntry = (Entry) glade.getWidget("tabooMainEntry");
		entry1 = (Entry) glade.getWidget("tabooEntry1");
		entry2 = (Entry) glade.getWidget("tabooEntry2");
		entry3 = (Entry) glade.getWidget("tabooEntry3");
		entry4 = (Entry) glade.getWidget("tabooEntry4");
		entry5 = (Entry) glade.getWidget("tabooEntry5");
		entry6 = (Entry) glade.getWidget("tabooEntry6");
		
		successfullAdd = (Label) glade.getWidget("successfullAdd");
		
		initialOverallRatingBox = (ComboBox) glade.getWidget("initialOverallRatingBox");
		
		// Current Card
		mainWord  = (Label) glade.getWidget("mainWord");
		label1  = (Label) glade.getWidget("label1");
		label2  = (Label) glade.getWidget("label2");
		label3  = (Label) glade.getWidget("label3");
		label4  = (Label) glade.getWidget("label4");
		label5  = (Label) glade.getWidget("label5");
		label6  = (Label) glade.getWidget("label6");
		cardNumReal = (Label) glade.getWidget("cardNumReal");
		currentTeamNumReal = (Label) glade.getWidget("currentTeamNumReal");
		currCardRatingValue = (Label) glade.getWidget("currCardRatingValue");
		mustSetOptionsNewGame = (Label) glade.getWidget("mustSetOptionsNewGame");
		
		
		correct = (Button) glade.getWidget("correct");

		
		// Options
		useDefaultOptions = (Button) glade.getWidget("useDefaultOptions");
		clearOptions = (Button) glade.getWidget("clearOptions");
		numTeamsBox = (ComboBox) glade.getWidget("numTeamsBox");
		numCardsBox = (ComboBox) glade.getWidget("numCardsBox");
		numSecondsBox = (ComboBox) glade.getWidget("numSecondsBox");
		maxDifficulty = (ComboBox) glade.getWidget("maxDifficulty");
		minOverallRatingBox = (ComboBox) glade.getWidget("minOverallRatingBox");
		
		// Score
		scoreLabel = (Label) glade.getWidget("scoreLabel");
		
		// Rating
		difficultyBoxRating = (ComboBox) glade.getWidget("difficultyBoxRating");
		overallBoxRating = (ComboBox) glade.getWidget("overallBoxRating");
		
		// Save/load
		saveButton = (Button) glade.getWidget("saveButton");
		loadButton = (Button) glade.getWidget("loadButton");

		
		/*
		 * Current Card Section
		 */
		
		/*
		 * Buttons
		 */
		correct.connect(new CLICKED() 
		{
            public void onClicked(Button source)
            {
            	/*
        		 * increase score for current team
        		 * increment current card # and
        		 * 		current team #
        		 * display another card
        		 * 
        		 */
            	if(numCards!=0)
            	{
            		teamStore.getTeam(currentTeam).incrementScore();
	            	drawNewCard();
	            }
            	else
            	{
            		mustSetOptionsNewGame.setLabel("Game finished, start a new game, or check your score");
            	}
            }
        });

		incorrect = (Button) glade.getWidget("incorrect");
		incorrect.connect(new CLICKED() 
		{
            public void onClicked(Button source) 
            {
            	/*
        		 * increment current card # and
        		 * 		current team #
        		 * Display another card
        		 */
            	if(numCards!=0)
            	{
	            	drawNewCard();
	            }
            	else
            	{
            		mustSetOptionsNewGame.setLabel("Game finished, start a new game, or check your score");
            	}
            }
        });
		
		newGame = (Button) glade.getWidget("newGame");
		newGame.connect(new CLICKED() 
		{
            public void onClicked(Button source) 
            {
            	/*
        		 * Display another card
        		 * Set score to 0 for all teams
        		 * set current card# and current team # to 0
        		 */
            	if(numTeamsBox.getActiveIter()==null||numCardsBox.getActiveIter()==null||
            			numSecondsBox.getActiveIter()==null||maxDifficulty.getActiveIter()==null)
            	{
            		mustSetOptionsNewGame.setLabel("You must set all options before starting a game");
            	}
        
            	else
            	{
            		switch(numTeamsBox.getActive())
            		{
	            		case 0:
	            			numTeams=2;
	            			break;
	            		case 1:
	            			numTeams=3;
	            			break;
	            		case 2:
	            			numTeams=4;
	            			break;
	            		case 3:
	            			numTeams=5;
	            			break;
	            		case 4:
	            			numTeams=6;
	            			break;
	            		default:
	            			System.out.println("switch statement problem");
	            			break;
            		}
            		switch(numCardsBox.getActive())
            		{
	            		case 0:
	            			numCards=5;
	            			break;
	            		case 1:
	            			numCards=10;
	            			break;
	            		case 2:
	            			numCards=15;
	            			break;
	            		case 3:
	            			numCards=20;
	            			break;
	            		case 4:
	            			numCards=25;
	            			break;
	            		case 5:
	            			numCards=30;
	            			break;
	            		case 6:
	            			numCards=35;
	            			break;
	            		case 7:
	            			numCards=40;
	            			break;
	            		case 8:
	            			numCards=45;
	            			break;
	            		case 9:
	            			numCards=50;
	            			break;
	            		default:
	            			System.out.println("switch statement problem");
	            			break;
            		}
            		// display another card
            		cardNumVal=0;
            		currentTeam=0;
            		
            		/*
            		 * TODO
            		 * should check validCardStore
            		 * for some reason that breaks it...
            		 */
            		if(cardStore.getArraySize()<numTeams)
            		{
            			mustSetOptionsNewGame.setLabel("There are not enough valid " +
            					" cards (with specified difficulty/overall rating)" +
            					" please add cards");
            		}
            		
            		else
            		{
	            		/*
	            		 * Remove all valid Cards for new
	            		 * valid cards in the new game
	            		 */
	            		validCardStore.clear();
	            		/*
	            		 * only show cards with specified rating/difficulty
	            		 * while(currentCard.getOverallRating())
	            		 */
	            		if(cardStore.getMinRatingMaxDiffCard(minOverallRatingBox.getActive()+1, maxDifficulty.getActive()+1)!=-1)
	            		{
	            			/*
	            			 * TODO
	            			 * goes out of bounds when i<=cardStore.getArraySize()
	            			 * which is what I think it needs to be else
	            			 * it misses the last item in the array
	            			 * need to figure out why
	            			 */
	            			for(int i=0; i<cardStore.getArraySize(); i++)
	                		{
	                			if(cardStore.getCard(i).getDifficultyRatingAvg()<=maxDifficulty.getActive()+1 &&
	                					cardStore.getCard(i).getOverallRatingAvg()>=minOverallRatingBox.getActive()+1)
	                			{
	                				validCardStore.addItem(cardStore.getCard(i));
	                			}
	                		}
	            			currentCard=validCardStore.getCard(validCardStore.getRandomCardNum());
	            		}
	            		else
	            		{
	            			mustSetOptionsNewGame.setLabel("No card exists with specified minRating and Max difficulty");
	            		}
	            		
            			drawNewCard();
	            		
	            		mustSetOptionsNewGame.setLabel("");
	            		
	            		/*
	            		 * Remove everything from teamArray
	            		 * to make room for new teams
	            		 * in the new game
	            		 */
	            		teamStore.clear();
	            		
	            		/*
	            		 * Create New Teams
	            		 * Since .getActive starts at 0 and we start at 2 we add 2
	            		 */
	            		for(int i=0; i<=numTeamsBox.getActive()+2; i++)
	            		{
	            			Team aTeam=new Team();
	            			teamStore.addItem(aTeam);
	            		}
	            		
	            		
            		}
            	}
            }
        });
		
		
		/*
		 * End Buttons
		 */
		
		/*
		 * End Current Card Section
		 */	
		
		
		/*
		 * Options Section
		 */
		
		/*
		 * Buttons
		 */
		
		useDefaultOptions.connect(new CLICKED()
		{
            public void onClicked(Button source) 
            {
            	numTeamsBox.setActive(0);
            	numCardsBox.setActive(0);
            	numSecondsBox.setActive(0);
            	maxDifficulty.setActive(4);
            	minOverallRatingBox.setActive(0);
            }
        });
		
		/*
		 * End Buttons
		 */
		
		/*
		 * End Options Section
		 */
		
		/*
		 * Add Card Section
		 */
		
		/*
		 * Buttons
		 */

		clearAddCard = (Button) glade.getWidget("clearAddCard");
		clearAddCard.connect(new CLICKED() 
		{
            public void onClicked(Button source) 
            {
            	/*
        		 * clear tabooEntry(1-6)
        		 * 
        		 */
            	clearAddCard();
            }
        });

		addCard = (Button) glade.getWidget("addCardButton");
		addCard.connect(new CLICKED() 
		{
            public void onClicked(Button source) 
            {
            	/*
            	 * Create card object from input
            	 * in tabooEntry(1-6) and insert
            	 * it into arrayStorage object
            	 * 	(when I figure out JDBC
            	 * 	it should be trivial to
            	 * 	move, hopefully)
            	 * 
            	 * check to see if word already
            	 * exists
            	 * 
            	 * display with successfullAdd label
            	 * that the current card was
            	 * added successfully
            	 * 
            	 * TODO: handle if some fields are left blank
            	 * 	(thus void)
        		 */
            	if(mainEntry.getText()==null||entry1.getText()==null||initialOverallRatingBox.getActiveIter()==null)
            	{
            		successfullAdd.setLabel("Please enter the main Word and at least one taboo word for that word" +
            				" and give the card an initial rating");
            	}
            	else if(entry2.getText()==null)
            	{
            		insCard=new Card(mainEntry.getText(),entry1.getText(),"","","","","",
            				5,initialOverallRatingBox.getActive()+1);
            		cardStore.addItem(insCard);
            		successfullAdd.setLabel("Card : "+mainEntry.getText()+" Successfully Added");
            	}
            	else if(entry3.getText()==null)
            	{
            		insCard=new Card(mainEntry.getText(),entry1.getText(),entry2.getText(),"","","","",
            				5,initialOverallRatingBox.getActive()+1);
            		cardStore.addItem(insCard);
            		successfullAdd.setLabel("Card : "+mainEntry.getText()+" Successfully Added");
            	}
            	else if(entry4.getText()==null)
            	{
            		insCard=new Card(mainEntry.getText(),entry1.getText(),entry2.getText(),
            				entry3.getText(),"","","",
            				5,initialOverallRatingBox.getActive()+1);
            		cardStore.addItem(insCard);
            		successfullAdd.setLabel("Card : "+mainEntry.getText()+" Successfully Added");
            	}
            	else if(entry5.getText()==null)
            	{
            		insCard=new Card(mainEntry.getText(),entry1.getText(),entry2.getText(),
            				entry3.getText(),entry4.getText(),"","",
            				5,initialOverallRatingBox.getActive()+1);
            		cardStore.addItem(insCard);
            		successfullAdd.setLabel("Card : "+mainEntry.getText()+" Successfully Added");
            	}
            	else if(entry6.getText()==null)
            	{
            		insCard=new Card(mainEntry.getText(),entry1.getText(),entry2.getText(),
            				entry3.getText(),entry4.getText(),entry5.getText(),"",
            				5,initialOverallRatingBox.getActive()+1);
            		cardStore.addItem(insCard);
            		successfullAdd.setLabel("Card : "+mainEntry.getText()+" Successfully Added");
            	}
            	else
            	{
            		insCard=new Card(mainEntry.getText(),entry1.getText(),
            				entry2.getText(),entry3.getText(),
            				entry4.getText(),entry5.getText(),
            				entry6.getText(),5,initialOverallRatingBox.getActive()+1);;
            		cardStore.addItem(insCard);
            		successfullAdd.setLabel("Card : "+mainEntry.getText()+" Successfully Added");
            		clearAddCard();
            	}
            	
            }
        });
		
		/*
		 * End Buttons
		 */
		/*
		 * End Add Card Section
		 */
		
		
		/*
		 * Score Section
		 */
		
		/*
		 * Buttons
		 */

		selectTeamBox = (ComboBox) glade.getWidget("selectTeamBox");
		selectTeamBox.connect(new CHANGED()
		{
			public void onChanged(ComboBox source)
			{
				if(selectTeamBox.getActive()+2>teamStore.getArraySize())
				{
					scoreLabel.setLabel("Team Does not exist");
				}
				else
				{
					scoreLabel.setLabel(Integer.toString(teamStore.getTeam(selectTeamBox.getActive()+1).getScore()));
				}
			}
        });
		
		/*
		 * End Buttons
		 */
		/*
		 * End Score Section
		 */
		
		/*
		 * Save/Load Section
		 */
		
		/*
		 * Buttons
		 */

		saveButton.connect(new CLICKED() 
		{
            public void onClicked(Button source) 
            {
            	/*
        		 * save cardStore to a file named objects
        		 * 
        		 */
            	try
            	{
            		// false means we will write to objects file
            		FileOutputStream fos = new FileOutputStream ("objects",false);
            		ObjectOutputStream oos = new ObjectOutputStream(fos);
            		
            		// write card objects to file
            		oos.writeObject(cardStore);
            		
            		// release resources associated with the objects file
            		oos.close();
            	}
            	
            	catch(FileNotFoundException fnfe)
            	{
            		System.out.println("unable to write object");
            	}
            	catch(IOException ioe)
            	{
            		ioe.printStackTrace();
            	}
            }
        });
		
		loadButton.connect(new CLICKED() 
		{
            public void onClicked(Button source) 
            {
            	/*
        		 * load a file named objects into cardStore
        		 * 
        		 */

            		FileInputStream fis = null;
					try {
						fis = new FileInputStream("objects");
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
            		ObjectInputStream ois = null;
					try {
						ois = new ObjectInputStream(fis);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

            		try {
						cardStore=(CardStorage) ois.readObject();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
            }
        });
		
		/*
		 * End Buttons
		 */
		/*
		 * End Save/Load Section
		 */
	}
	
	/**
	 * Draws up a Random Card meeting the requirements of the
	 * options menu
	 * <p>
	 * Also takes care of setting the current team and such
	 * <p>
	 * Also takes care of handling how the current card was rated
	 * when correct/incorrect buttons are clicked
	 */

	public void drawNewCard()
	{
		if(currentTeam==numTeams)
		{
			currentTeam=1;
		}
		else
		{
			currentTeam++;
		}

		cardNumVal++;
		numCards--;

		currentCard=validCardStore.getCard(validCardStore.getRandomCardNum());


		if(difficultyBoxRating.getActiveIter()!=null && difficultyBoxRating.getActive()!=0)
		{
			currentCard.incNumDifficultyRatings();
			switch(difficultyBoxRating.getActive())
			{
			case 0:
				break;
			case 1:
				currentCard.setDifficultyRating(1);
				break;
			case 2:
				currentCard.setDifficultyRating(2);
				break;
			case 3:
				currentCard.setDifficultyRating(3);
				break;
			case 4:
				currentCard.setDifficultyRating(4);
				break;
			case 5:
				currentCard.setDifficultyRating(5);
				break;
			default:
				System.out.println("switch statement problem: Difficulty" +
						" Rating will be affected");
				break;
			}
			difficultyBoxRating.setActive(0);
		}
		if(overallBoxRating.getActiveIter()!=null && overallBoxRating.getActive()!=0)
		{
			currentCard.incNumOverallRatings();
			switch(overallBoxRating.getActive())
			{
			case 0:
				break;
			case 1:
				currentCard.setOverallRating(1);
				break;
			case 2:
				currentCard.setOverallRating(2);
				break;
			case 3:
				currentCard.setOverallRating(3);
				break;
			case 4:
				currentCard.setOverallRating(4);
				break;
			case 5:
				currentCard.setOverallRating(5);
				break;
			default:
				System.out.println("switch statement problem: Overall" +
						" Rating will be affected");
				break;
			}
			overallBoxRating.setActive(0);
		}
		mainWord.setLabel(currentCard.getBase());
		label1.setLabel(currentCard.getWord1());
		label2.setLabel(currentCard.getWord2());
		label3.setLabel(currentCard.getWord3());
		label4.setLabel(currentCard.getWord4());
		label5.setLabel(currentCard.getWord5());
		label6.setLabel(currentCard.getWord6());
		currCardRatingValue.setLabel(Double.toString(currentCard.getOverallRatingAvg()));
		cardNumReal.setLabel(Integer.toString(cardNumVal));
		currentTeamNumReal.setLabel(Integer.toString(currentTeam));
	}
	
	  /**
     * When a card is Added, fields are blanked to allow
     * the user to enter another card easily
     * <p>
     * Also clears the fields if the user clicks the clear
     * button on the add card notebook tab
     */

	public void clearAddCard()
	{
		/*
		 * clear tabooEntry(1-6)
		 * 
		 */
		mainEntry.setText("");
    	entry1.setText("");
    	entry2.setText("");
    	entry3.setText("");
    	entry4.setText("");
    	entry5.setText("");
    	entry6.setText("");
	}
	
	public static void main(String[] args)
	{
		Simple s;
		Gtk.init(args);
		try
		{
			s=new Simple();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		Gtk.main();
	}

}
